package Base.多线程同步.死锁问题;

/**
 * @author 陈鹏
 */
public class Example16 {
    public static void main(String[] args) {
        //线程1，flag为true，运行if中的内容
        DeadLockThread thread1 = new DeadLockThread(true);
        //线程2，flag为false，运行else中的内容
        DeadLockThread thread2 = new DeadLockThread(false);
        new Thread(thread1, "Chinese").start();
        new Thread(thread2, "American").start();
    }
}

class DeadLockThread implements Runnable {
    //定义两个类作为锁
    static Object chopsticks = new Object();
    static Object knifeAndFork = new Object();
    private boolean flag;
    //有参构造方法，给flag赋值
    DeadLockThread(boolean flag) {
        this.flag = flag;
    }
    @Override
    public void run() {
        if (flag) {
            while (true) {
                //
                synchronized (chopsticks) {
                    System.out.println(Thread.currentThread().getName() + "---if---chopsticks");
                    synchronized (knifeAndFork) {
                        System.out.println(Thread.currentThread().getName() + "---if---knifeAndFork");
                    }
                }
            }
        } else {
            while (true) {
                synchronized (knifeAndFork) {
                    System.out.println(Thread.currentThread().getName() + "---else---knifeAndFork");
                    synchronized (chopsticks) {
                        System.out.println(Thread.currentThread().getName() + "---else---chopsticks");
                    }
                }
            }
        }
    }
}

